<template>
  <div class="common-title">
    床位预约
  </div>
  <div class="time-line flex ">
    <div class="time-top flex space-between align-center">
      <el-button @click="nextOrPrevDayArr('prev')" :icon="ArrowLeftBold" size="default" style="padding: 0 0 0 4px;" />
      <div class="time-list" style="white-space: nowrap;">
        <div class="time-item" v-for="(item, index) in state.dayArr" :key="index"
          :class="item == state.checkedDay ? 'active' : ''" @click="changeDay(item)">
          {{ formatValue(item) }}
        </div>
      </div>
      <el-button @click="nextOrPrevDayArr('next')" :icon="ArrowRightBold" size="default" style="padding: 0 0 0 4px;" />
    </div>
  </div>


  <div class="area-slot flex align-center">
    <el-radio-group v-model="state.hospitalAreaId" size="default" @change="searchBedChange">
      <el-radio-button v-for="(item, index) in state.hospitalAreaList" :key="index" :label="item.id" border>{{
        item.name }}</el-radio-button>
    </el-radio-group>
    <!-- <span style="margin-left:40px;">床位状态</span>
    <el-select v-model="state.bedStatus" placeholder="请选择床位状态" size="default" style="width: 150px;" clearable
      @change="searchBedChange">
      <el-option label="未预约" :value="0"></el-option>
      <el-option label="已预约" :value="1"></el-option>
    </el-select> -->
  </div>
  <div class="bed-box" v-loading="state.bedLoading" element-loading-background="#fff">
    <div class="bed-list">
      <div class="bed-item flex " v-for="(item, index) in state.bedList" :key="index"
        :class="item.patientRecord ? 'selected' : ''">

        <!-- 如果为可选 -->
        <div v-if="!item.patientRecord" class="item-content" :class="item.isDisable == 1?'disabled':''" @click="changeSelectBed(item)">
          <div class="nfo-box no-user-box flex justify-center align-center">
            <div class="no-user-center flex ">
              <div class="bed-number">
                {{ item.number + '床' }}
              </div>
              <img v-if="item.isDisable == 1" :src="lock" alt="" class="re-lock">
              <div v-else class="re-btm">床位预约</div>
            </div>
          </div>
        </div>

        <!-- 不可选 -->
        <div v-else class="item-content " :class="item.patientRecord.id !== state.detailId ? 'disabled' : ''">
          
          <!-- 若当前登录人为管理员或该患者主刀医生 才可看见详细信息 否则只显示占位 -->
          <div v-if="currentUserId == item.patientRecord.operation.chiefDoctorId || isAdmin" class="info-box">
            <div class="bed-number">
              {{ item.number + '床' }}
            </div>
            <div class="patient-infos">

              <span class="top-line flex space-between align-center">
                <span>{{ item.patientRecord.patient.name }}</span>
                <span>{{ sexObj[item.patientRecord.patient.gender] }}</span>
                <span>{{ item.patientRecord.age ? item.patientRecord.age : '-' }}</span>
              </span>

              <div class="flex space-between align-start" style="margin:1.5% 0;">
                <el-tooltip class="box-item" effect="dark" :content="item.patientRecord.preDiagnosis" :placement="top">
                  <span class="pre ellipsis">{{ item.patientRecord.preDiagnosis }}</span>
                </el-tooltip>
                <span class="flex align-center">
                  <span class="anesthesia"> {{
                    item.patientRecord.anesthesiaAssessment &&
                    item.patientRecord.anesthesiaAssessment.anesthesiaMode ?
                    item.patientRecord.anesthesiaAssessment.anesthesiaMode.name : '-'
                  }}</span>
                  |
                  <span class="doctor-name ellipsis"> {{
                    item.patientRecord.operation && item.patientRecord.operation.chiefDoctor ?
                    item.patientRecord.operation.chiefDoctor.name : '-'
                  }}</span>
                </span>

              </div>

              <div class="flex space-between">
                <el-tooltip class="box-item" effect="dark" :content="item.patientRecord.operation && item.patientRecord.operation.operation ?
                      item.patientRecord.operation.operation.name : '-'" :placement="top">
                  <div class="operation-name ellipsis">
                    {{
                      item.patientRecord.operation && item.patientRecord.operation.operation ?
                      item.patientRecord.operation.operation.name : '-'
                    }}
                  </div>
                </el-tooltip>
                <div class="cancel-apply" v-if="item.patientRecord && (state.detailId === item.patientRecord.id)"
                  @click.stop="cancelApplyBed(item)">
                  取消预约
                </div>
              </div>


            </div>
          </div>
          <div v-else class="info-box disabled">
            <div class="bed-number">
              {{ item.number + '床' }}
            </div>
            <img class="bed-img" :src="icon" alt="">
          </div>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup name="operationOrder">
import dayjs from 'dayjs'
import { formatWeedDay } from '/@/utils/formatTime';
import {
  ArrowLeftBold,
  ArrowRightBold,
  Postcard,
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus';
import { toolsApi } from '/@/api/tools'
import { dsApi } from '/@/api/ds/index'
import { usePatientDetail } from '/@/stores/patientDetail';
import { storeToRefs } from 'pinia'
import { useUserInfo } from '/@/stores/userInfo'
import icon from '/@/assets/bed-lock.png';
import { throttle } from '/@/utils/toolsValidate';
import lock from '/@/assets/lock.png';

const UserInfoStores = useUserInfo()
const { userInfos } = storeToRefs(UserInfoStores);

const stores = usePatientDetail();
const { sexObj } = storeToRefs(stores);
const route = useRoute();
const props = defineProps({
  datas: {
    type: Object,
    default: () => { },
  },
});

const state = reactive({
  detailId: '',
  checkedDay: null,
  dayArr: [],
  period: '上午',
  hospitalAreaId: '1',
  operatRoomList: [

  ],
  operationRoomsLoading: false,
  bedStatus: '',
  bedList: [

  ],
  bedLoading: false,
  hospitalAreaList: [],
  opListCollType: false // false 收起 true 展开
})


// 页面加载时
onMounted(() => {
  state.detailId = route.query.id
  getDays()
  getOperationRoomDatas()
  getHospitalArea()
  getBedList()
});

// 是否为管理员
const isAdmin = computed(() => {
  const hasAdmin = userInfos.value.role.find(item=>{
    return item.slug == 'administrator'
  })

  if(hasAdmin && hasAdmin != undefined){
    return true
  }else{
	  return false;
  }
});

const currentUserId = computed(() => {
	return userInfos.value.id;
});

const getDays = () => {
  console.log(props.datas.operation.operationAt)
  const operationAt = props.datas.operation && props.datas.operation.operationAt ? props.datas.operation.operationAt : dayjs()
  const dayArr = []
  dayArr.push(dayjs(operationAt).startOf('day').unix())
  dayArr.push(dayjs(operationAt).startOf('day').add(1, "days").unix())
  dayArr.push(dayjs(operationAt).startOf('day').add(2, "days").unix())
  dayArr.push(dayjs(operationAt).startOf('day').add(3, "days").unix())
  dayArr.push(dayjs(operationAt).startOf('day').add(4, "days").unix())
  dayArr.push(dayjs(operationAt).startOf('day').add(5, "days").unix())
  dayArr.push(dayjs(operationAt).startOf('day').add(6, "days").unix())
  state.checkedDay = dayjs(operationAt).startOf('day').unix()
  state.dayArr = dayArr
}

const formatValue = (value) => {
  return dayjs(value * 1000).format("M.DD") + ' ' + '（' + formatWeedDay(dayjs(value * 1000).day()) + '）'
}

const changeDay = (value) => {
  state.checkedDay = value
  // getOperationRoomDatas()
  getBedList()
}

const periodChange = () => {
  getOperationRoomDatas()
}

const changeOpListColl = () => {
  state.opListCollType = !state.opListCollType
}

const nextOrPrevDayArr = (type) => {
  if (type == 'next') {
    const nextDayArr = []
    nextDayArr.push(state.dayArr[5] + 86400)
    nextDayArr.push(state.dayArr[5] + 86400 * 2)
    nextDayArr.push(state.dayArr[5] + 86400 * 3)
    nextDayArr.push(state.dayArr[5] + 86400 * 4)
    nextDayArr.push(state.dayArr[5] + 86400 * 5)
    nextDayArr.push(state.dayArr[5] + 86400 * 6)
    nextDayArr.push(state.dayArr[5] + 86400 * 7)
    state.dayArr = nextDayArr
    state.checkedDay = nextDayArr[0]
  } else {
    const prevDayArr = []
    prevDayArr.push(state.dayArr[0] - 86400 * 7)
    prevDayArr.push(state.dayArr[0] - 86400 * 6)
    prevDayArr.push(state.dayArr[0] - 86400 * 5)
    prevDayArr.push(state.dayArr[0] - 86400 * 4)
    prevDayArr.push(state.dayArr[0] - 86400 * 3)
    prevDayArr.push(state.dayArr[0] - 86400 * 2)
    prevDayArr.push(state.dayArr[0] - 86400)

    state.dayArr = prevDayArr
    state.checkedDay = prevDayArr[0]
  }
  getBedList()
}


const changeSelectOp = (operationRoom, num) => {
  const apiData = {
    patientRecordId: props.datas.id,
    operationAt: dayjs(state.checkedDay * 1000).format('YYYY-MM-DD'),
    period: state.period == '上午' ? 'AM' : 'PM',
    operationRoom: operationRoom,
    num: num
  }

  dsApi().recordOperation(apiData).then(res => {
    ElMessage.success('操作成功');
    getOperationRoomDatas()
  }).catch(() => {

  })
}




const changeSelectBed = throttle((item) => {
  if(!isAdmin.value && (currentUserId.value != props.datas.operation.chiefDoctorId)){
    ElMessage.warning('无操作权限');
    return;
  }
  if (item.isDisable == 1) {
    ElMessage.warning('该床位已被管理员禁用');
    return
  }
  const apiData = {
    patientRecordId: props.datas.id,
    hospitalAreaId: state.hospitalAreaId,
    hospitalBedId: item.id,
    operationAt: dayjs(state.checkedDay * 1000).format('YYYY-MM-DD'),
  }

  dsApi().recordBed(apiData).then(res => {
    ElMessage.success('操作成功');
    getBedList()
  }).catch(() => {

  })
} ,500)

const cancelApplyBed = () => {
  const apiData = {
    prid: props.datas.id,
  }

  dsApi().cancelBed(apiData).then(res => {
    ElMessage.success('操作成功');
    getBedList()
  }).catch(() => {

  })
}

const searchBedChange = () => {
  getBedList()
}




const getOperationRoomDatas = () => {
  state.operationRoomsLoading = true
  const apiData = {
    operationAt: dayjs(state.checkedDay * 1000).format('YYYY-MM-DD'),
    period: state.period == '上午' ? 'AM' : 'PM'
  }
  toolsApi().operationRooms(apiData).then(res => {
    state.operationRoomsLoading = false
    state.operatRoomList = res.data
  }).catch(() => {
    state.operationRoomsLoading = false
  })

}

const getHospitalArea = () => {
  toolsApi().hospitalArea().then(res => {
    state.hospitalAreaList = res.data
  }).catch(() => {
  })
}

const getBedList = () => {
  state.bedLoading = true
  const apiData = {
    hospitalAreaId: state.hospitalAreaId,
    status: state.bedStatus,
    operationAt: dayjs(state.checkedDay * 1000).format('YYYY-MM-DD'),
  }
  toolsApi().hospitalBeds(apiData).then(res => {
    state.bedLoading = false
    state.bedList = res.data
  }).catch(() => {
    state.bedLoading = false
  })
}

</script>

<style lang="scss" scoped>
.area-slot {
  margin: 20px 0;
}

.time-line {
  flex-wrap: wrap;
  padding: 0px 0;
  margin-top: 15px;

  .time-top,
  .time-bottom {
    width: 100%;
  }

  .time-list {
    width: calc(100% - 120px);
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    gap: 15px;
    overflow-x: auto;
    overflow-y: hidden;
  }

  .time-item {
    position: relative;
    height: 44px;
    text-align: center;
    line-height: 44px;
    background-color: #F9F9F9;
    color: #333;
    border-radius: 8px;
    border: 1px solid #C9C9C9;
    padding: 0 10px;
    cursor: pointer;
    font-weight: 500;


    &.active {
      color: #409EFF;
      background-color: #fff;
      border: 1px solid #409EFF;
    }

  }


}

.op-room-list {
  margin-bottom: 30px;

  .op-room-item {
    margin-bottom: 32px;

    .item-left {
      flex-wrap: wrap;
      width: 180px;
      height: 227px;
      border-radius: 8px;
      background-color: rgba(245, 245, 245, 1);
      color: rgba(48, 129, 244, 1);

      .icon {
        width: 100%;
        text-align: center;
        margin-top: 60px;
      }

      .name {
        width: 100%;
        text-align: center;
        margin-top: 30px;
      }
    }

    .item-right {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 22px;
      width: calc(100% - 200px);

      .op-item {
        border: 1px solid rgba(199, 199, 208, 1);
        border-radius: 8px;
        line-height: 60px;

        &.selected {
          background-color: rgba(244, 250, 255, 1);
          color: rgba(48, 129, 244, 1);
          border: 2px solid rgba(48, 129, 244, 1);
        }

        .content {
          width: 100%;
          cursor: pointer;
          padding: 0 20px;

          &.disabled {
            cursor: no-drop;
          }
        }
      }
    }
  }
}

.bed-box {
  width: 100%;
  height: 370px;
  margin-top: 8px;
}

.bed-list {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  // grid-template-rows: repeat(7, 1fr);
  gap: 0px;
  width: 100%;
  height: 100%;
  border: 0.5px solid #CECECE;

  .bed-item {
    flex-direction: column;
    // height: 74px;
    border: 0.5px solid #CECECE;
    background: #F9F9F9;
    padding: 6px;

    &.selected {
      background-color: rgba(166, 202, 240, 0.2);

    }

    .item-content {
      position: relative;
      display: flex;
      flex-direction: column;
      height: 100%;
      cursor: pointer;

      &.disabled {
        cursor: no-drop;
      }

      .no-user-box {
        position: relative;
        width: 100%;
        height: 100%;

        .no-user-center {
          position: absolute;
          left: 50%;
          transform: translateX(-50%);
          top: 0;
          flex-direction: column;

          .bed-number {
            color: #000;
            font-weight: 500;
            text-align: center;
          }

          .re-btm {
            width: 88px;
            height: 28px;
            background: #FFFFFF;
            border-radius: 2px;
            border: 1px dashed #D9D9D9;
            text-align: center;
            line-height: 26px;
            margin-top: 2%;
            color: #666;
          }
        }
      }

      .info-box {
        display: flex;
        justify-content: center;
        align-items: center;
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;

        &.disabled{
          cursor: no-drop;
        }

        .bed-img{
          width: 35px;
          height: 35px;
        }

        .bed-number {
          position: absolute;
          right: -8px;
          top: -8px;
          width: 51px;
          height: 18px;
          background: #0077D7;
          box-shadow: 0px 2px 4px 0px rgba(26, 79, 0, 0.13);
          border-radius: 11px 0px 11px 11px;
          color: #fff;
          font-size: 12px;
          text-align: center;
        }

        .patient-infos {
          width: 100%;
          height: 100%;
          font-size: 12px;

          .cancel-apply {
            padding: 2px 10px;
            background-color: #F56C6C;
            color: #fff;
            border-radius: 11px;
            white-space: nowrap;
            transform: scale(0.9);
          }

          .pre {
            width: 49%;
          }

          .anesthesia {
            display: inline-block;
            max-width: 40px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          .top-line {
            width: 60%;
          }


        }
      }
    }



  }
}
</style>
